<template>
  <div class="center">
    <n-card :bordered="false">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        :submitButtonText="'查询'"
        :show-feedback="false"
        :resetButtonText="'重置'"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        :pagination="pagination"
        :scroll-x="1600"
      >
        <template #tableTitle>
          <n-space>
            <n-button size="small" @click="addTable"> 新增 </n-button>
            <n-button size="small"> 批量导入 </n-button>
          </n-space>
        </template>
        <!-- <template #toolbar>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </template> -->
      </BasicTable>
    </n-card>
    <Model
      :showModal="showModal"
      :FormData="FormData"
      :formValue="formValue"
      :title="title"
      :rules="rules"
      @ModelClick="ModelClick"
      @close="close"
    >
    </Model>
    <ModelBox
      :ModelBox="ModelBox"
      :center="center"
      :title="title"
      @determine="determine"
      @close="close"
    ></ModelBox>
  </div>
</template>

<script lang="ts">
import { h, defineComponent, reactive, ref, onMounted } from 'vue';
import { useMessage,NTag } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Form/index';
import { fetchUserListPage,addUser,deleteUser,updateUserStatus,updateUser } from '@/api/UserManagement/index';//用户列表接口
import { fetchRoleTree } from '@/api/Role/index';//角色接口
import { fetchDepartmentList } from '@/api/Department/index';//角色接口
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { Model } from '@/components/Model';
import { ModelBox } from '@/components/ModelBox';
export default defineComponent({
  name:'SystemSettingUserList',
  components: {
    BasicTable,
    BasicForm,
    PlusOutlined,
    Model,
    ModelBox,
  },
  setup() {
    const columns = [
      {
        type: 'selection',
        fixed: 'left',
      },
      {
        title: '序号',
        key: 'Serial',
        width:100,
      },
      {
        title: '账号',
        key: 'userName',
        width:200,
        render (row) {
          if(row.userName){
            return row.userName
          }else {
            return '-'
          }
        }
      },
      {
        title: '姓名',
        key: 'name',
        width:200,
        render (row) {
          if(row.name){
            return row.name
          }else {
            return '-'
          }
        }
      },
      {
        title: '所属部门',
        width:300,
        key: 'departmentList',
        render (row) {
          const tags = row.departmentList.map((tagKey) => {
            return h(
              NTag,
              {
                style: {
                  marginRight: '6px'
                },
                type: 'info'
              },
              {
                default: () => tagKey.departmentName
              }
            )
          })
          return tags
        }
      },
      {
        title: '角色',
        key: 'roleList',
        width:300,
        render (row) {
          const tags = row.roleList.map((tagKey) => {
            return h(
              NTag,
              {
                style: {
                  marginRight: '6px'
                },
                type: 'info'
              },
              {
                default: () => tagKey ? tagKey.roleName : '-'
              }
            )
          })
          return tags
        }
      },
      {
        title: '状态',
        key: 'address',
        width:100,
        render (row) {
          if(row.isEnable == 1){
            return '可用'
          }else {
            return '停用'
          }
        }
      },
    ];
    const actionRef = ref();
    const router = useRouter();
    const formRef: any = ref(null);
    const center = ref(null);
    const message = useMessage();
    const title = ref(null);
    const showModal = ref(false);
    const ModelBox = ref(false);
    const formBtnLoading = ref(false);
    const formValue = ref({});
    const FormData = ref([
      {
        label: '账号',
        type: 'n-input',
        enName: 'userName',
        clearable: true,
        size: 'small',
        show:true,
        placeholder: '请输入账号',
        span: 12,
      },
      {
        label: '姓名',
        type: 'n-input',
        enName: 'name',
        clearable: true,
        size: 'small',
        placeholder: '请输入姓名',
        show:true,
        span: 12,
      },
      {
        label: '密码',
        type: 'n-input',
        enName: 'password',
        clearable: true,
        show:false,
        size: 'small',
        placeholder: '请输入密码',
        span: 12,
      },
      {
        label: '用户组',
        type: 'n-tree-select',
        enName: 'departmentListaaa',
        checkStrategy:'parent',
        clearable: true,
        checkable: true,
        cascade: true,
        multiple: true,
        size: 'small',
        show:true,
        placeholder: '请选择分组',
        span: 24,
      },
      // {
      //   label: '角色',
      //   type: 'n-tree-select',
      //   enName: 'roleListaaa',
      //   checkStrategy:'child',
      //   multiple: true,
      //   clearable: true,
      //   checkable: true,
      //   cascade: true,
      //   size: 'small',
      //   show:true,
      //   placeholder: '请选择角色',
      //   span: 24,
      // },
    ]);
    const formParams = ref({
      name: '',
      address: '',
      date: null,
    });
    const params = ref({size : 10, page:1});
    const Obj = ref({})
    const actionColumn = reactive({
      width: 220,
      title: '操作',
      key: 'action',
      fixed: 'right',
      render(record) {
        return h(TableAction as any, {
          text: true,
          actions: [
            {
              label: '查看',
              type: 'primary',
              text: true,
              onClick: see.bind(null, record),
            },
            {
              label: '编辑',
              type: 'primary',
              text: true,
              onClick: handleEdit.bind(null, record),
            },
            {
              label: record.isEnable == 1 ? '停用' : '启用',
              type: 'primary',
              text: true,
              onClick: Deactivate.bind(null, record),
            },
            {
              label: '删除',
              type: 'primary',
              text: true,
              onClick: handleDelete.bind(null, record),
            },
          ],
          select: (key) => {
            message.info(`您点击了，${key} 按钮`);
          },
        });
      },
    });
    const schemas = [
      {
        field: 'isEnable',
        component: 'NSelect',
        label: '状态',
        size: 'small',
        componentProps: {
          placeholder: '请选择状态',
          options: [
            {
              label: '可用',
              value: 1,
            },
            {
              label: '停用',
              value: 0,
            },
          ],
        },
      },
    ];
    const [register, {}] = useForm({
      gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
      labelWidth: 80,
      schemas,
    });
    const loadDataTable = async (res) => {
      const data = await fetchUserListPage( {...params.value ,...res } );
      data.list.map((res,index) => {
          res.Serial = ++ index
      })
      return data
    };

    const Deactivate = (record: Recordable) => {
      Obj.value = record
      ModelBox.value = true;
      title.value = '停用&启用';
      center.value = '是否确定要停用&启用';
    };

    const handleEdit = (record: Recordable) => {
      title.value = '编辑用户';
      FormData.value.map((res) => {
        if(res.enName == 'password'){
          res.show = false;
        }
        res.disabled = false;
      });
      record.roleListaaa = record.roleList.map((res) => {
        return res.id
      })
      record.departmentListaaa = record.departmentList.map((res) => {
        return res.id
      })
      formValue.value = record
      showModal.value = true;
    };

    const handleDelete = (record: Recordable) => {
      Obj.value = record
      ModelBox.value = true;
      title.value = '删除';
      center.value = '是否确定要删除?';
    };

    const see = async (record: Recordable) => {
      title.value = '查看用户';
      FormData.value.map((res) => {
        res.disabled = true;
        if(res.enName == 'password'){
          res.show = false;
        }
      })
      record.roleListaaa = record.roleList.map((res) => {
        return res.id
      });
      record.departmentListaaa = record.departmentList.map((res) => {
        return res.id
      })
      formValue.value = record
      showModal.value = true;
    };

    //停用启用 删除确定按钮
    const determine = async(e) => {
      ModelBox.value = e;
      if(title.value == '删除') {
        await deleteUser(Obj.value.id);
        actionRef.value.reload();
      }else if(title.value == '停用&启用') {
        await updateUserStatus(Obj.value.id);
        actionRef.value.reload();
      }
    }


    const departmentData = ref([])
    const ModeldepartmentData = ref([]);
    //获取角色和所属部门
    const roleDepartment = async () => {
      const options = ref([]);
      const res = await fetchRoleTree();
      ModeldepartmentData.value = await fetchDepartmentList();
      //部门数据处理
      ModeldepartmentData.value.map((res) => {
        if(res.parentId == '0'){
          departmentData.value.push({
            label:res.departmentName,
            key:res.id,
            id:res.id
          })
        }
      });
      let request = await DepartmentRecursion(departmentData.value);
      //处理角色数据格式
      options.value = res.map((r) => {
        return {
            label:r.roleGroupName,
            key:r.roleGroupId,
            children:r.roleList
        }
      });
      options.value.map((res) => {
        if(res.children.length == 0){
          delete res.children
        } else {
          res.children = res.children.map((r) => {
            return {
              label:r.roleName,
              key:r.id
            }
          })
        }
      })
      FormData.value.map((res) => {
        if(res.enName == 'roleListaaa') {
          //角色赋值
          res.options = options
        }
        if(res.enName == 'departmentListaaa') {
          //部门赋值
          res.options = request
        }
      })
    };
    //部门递归
    const DepartmentRecursion = async (data) => {
      try {
        for(var i = 0; i < data.length; i ++){
            for (var j = 0; j < ModeldepartmentData.value.length; j++) {
              if(ModeldepartmentData.value[j].parentId == data[i].id){
                if (data[i].hasOwnProperty('children')) {
                  data[i].children.push({
                    label:ModeldepartmentData.value[j].departmentName,
                    key:ModeldepartmentData.value[j].id,
                    id:ModeldepartmentData.value[j].id
                  })
                } else {
                  data[i].children = []
                  data[i].children.push({
                    label:ModeldepartmentData.value[j].departmentName,
                    key:ModeldepartmentData.value[j].id,
                    id:ModeldepartmentData.value[j].id
                  })
                }
              }
            }
          if(data[i].children){
            // children若不为空数组，则继续递归调用本方法
            DepartmentRecursion(data[i].children);
          }
        }
      } catch(e){
        console.log(e)
      }
      return data
    }
    //查询
    const handleSubmit = (row) => {
      try {
        params.value = { ...params.value, ...row };
        actionRef.value.reload();
      } catch (e) {
        console.error(e)
      }
    };
    //重置
    const handleReset = (row) => {
        params.value = {}
        actionRef.value.reload();
    }
    //新增
    const addTable = async () => {
      FormData.value.map((res) => {
        if(res.enName == 'password'){
          res.show = true;
        }
        res.disabled = false;
      });
      formValue.value = {}
      title.value = '新建用户';
      showModal.value = true;
    };

    //模态框确定
    const ModelClick = async (e) => {
      if(title.value == '新建用户'){
        const Obj = ref({});
        Obj.value.id = formValue.value.id
        Obj.value.isEnable = formValue.value.isEnable
        Obj.value.name = formValue.value.name
        Obj.value.userName = formValue.value.userName
        Obj.value.password = formValue.value.password
        Obj.value.departmentList = formValue.value.departmentListaaa;
        Obj.value.roleList = formValue.value.roleListaaa;
        await addUser(Obj.value);
      }else if(title.value == '编辑用户' ){
        const Obj = ref({});
        Obj.value.id = formValue.value.id
        Obj.value.isEnable = formValue.value.isEnable
        Obj.value.name = formValue.value.name
        Obj.value.userName = formValue.value.userName
        Obj.value.password = formValue.value.password
        Obj.value.departmentList = formValue.value.departmentListaaa;
        Obj.value.roleList = formValue.value.roleListaaa;
        await updateUser(Obj.value);
      }
      actionRef.value.reload();
      showModal.value = e;
      ModelBox.value = e;
    };
    //模态框关闭
    const close = (e) => {
      showModal.value = e;
      ModelBox.value = e;
    }
    onMounted(() => {
      roleDepartment();
    })
    return {
      rules: {
        name: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error('请输入姓名')
              } else if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
                return new Error('姓名应该为中文')
              }
              return true
            },
            trigger: ['input', 'blur']
          }
        ],
        userName: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error('请输入账号')
              } else if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(value)) {
                return new Error('请输入正确的手机号码')
              }
              return true
            },
            trigger: ['input', 'blur']
          }
        ],
        password: [
          {
            required: true,
            validator (rule, value) {
              if (!value) {
                return new Error('请输入密码')
              } else if (!/^(\w){6,20}$/.test(value)) {
                return new Error('只能输入6-20个字母、数字、下划线')
              }
              return true
            },
            trigger: ['input', 'blur']
          }
        ],
        departmentListaaa: {
          type:'array',
          required: true,
          message: '请选择部门',
          trigger: ['blur', 'change'],
        },
        roleListaaa: {
          type:'array',
          required: true,
          message: '请选择角色',
          trigger: ['blur', 'change'],
        },
      },
      handleReset,
      schemas,
      router,
      formRef,
      Obj,
      ModeldepartmentData,
      departmentData,
      message,
      actionRef,
      showModal,
      ModelBox,
      formBtnLoading,
      formParams,
      params,
      actionColumn,
      register,
      loadDataTable,
      Deactivate,
      handleEdit,
      handleDelete,
      see,
      columns,
      handleSubmit,
      determine,
      ModelClick,
      close,
      addTable,
      title,
      FormData,
      formValue,
      center,
    };
  },
});
</script>

<style lang="less" scoped>
.center :deep .n-card {
  margin: 0 0 20px 0;
}
</style>
